import { PlusOutlined } from '@ant-design/icons';
import { Button, message, Drawer, Modal } from 'antd';
import React, { useState, useRef } from 'react';
import { PageContainer, FooterToolbar } from '@ant-design/pro-layout';
import type { ProColumns, ActionType } from '@ant-design/pro-table';
import ProTable from '@ant-design/pro-table';
import type { ProDescriptionsItemProps } from '@ant-design/pro-descriptions';
import ProDescriptions from '@ant-design/pro-descriptions';
import { removeRule } from '@/services/ant-design-pro/api';
import { menuTreeListUsingGET } from '@/services/swagger/menu';
import { fixMenuItemIcon } from '@/utils/fixMenuItemIcon';
import { ModalForm, ProFormText, ProFormTextArea } from '@ant-design/pro-form';
import IconPreview from '@/components/IconPreview';

/**
 * 添加节点
 *
 * @param fields
 */

const handleAdd = async (fields: MenuVo) => {
  const hide = message.loading('正在添加');

  try {
    // await addRule({ ...fields });
    hide();
    message.success('添加成功');
    return true;
  } catch (error) {
    hide();
    message.error('添加失败请重试！');
    return false;
  }
};

/**
 *  Delete node
 * @zh-CN 删除节点
 *
 * @param selectedRows
 */

const handleRemove = async (selectedRows: API.MenuVo[]) => {
  const hide = message.loading('正在删除');
  if (!selectedRows) return true;

  try {
    await removeRule({
      key: selectedRows.map((row) => row.key),
    });
    hide();
    message.success('Deleted successfully and will refresh soon');
    return true;
  } catch (error) {
    hide();
    message.error('Delete failed, please try again');
    return false;
  }
};

const Menu: React.FC = () => {

  /** 新建窗口的弹窗 */
  const [createModalVisible, handleModalVisible] = useState<boolean>(false);
  const [iconPreviewVisible, handleIconVisible] = useState<boolean>(false);

  const [showDetail, setShowDetail] = useState<boolean>(false);
  const actionRef = useRef<ActionType>();
  const [currentRow, setCurrentRow] = useState<API.MenuVo>();
  const [selectedRowsState, setSelectedRows] = useState<API.MenuVo[]>([]);

  const selectIcon = (icon: string) => {
    console.log('选中的图标', icon)
    handleIconVisible(false)
    return ''
  }

  const columns: ProColumns<API.MenuVo>[] = [
    {
      title: '菜单名称',
      dataIndex: 'name',
      tip: 'The rule name is the unique key'
    },
    {
      title: '菜单图标',
      dataIndex: 'icon',
      search: false,
      render: (_, record) => (
        fixMenuItemIcon(record.icon || '')
      )
    },
    {
      title: '路由地址',
      search: false,
      copyable: true,
      dataIndex: 'path',
      // render: (_, record) => <Tag color={'green'}>{record.path}</Tag>
    },
    {
      title: '排序',
      search: false,
      dataIndex: 'sort',
      sorter: true
    },
    {
      title: '创建时间',
      search: false,
      dataIndex: 'createTime',
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      render: (_, record) => [
        <a
          key="view"
          onClick={() => {
            setCurrentRow(record);
            setShowDetail(true);
          }}
        >
          查看详情
        </a>,
      ],
    },
  ];
  return (
    <PageContainer>
      <ProTable<API.MenuVo, API.menuListPageUsingGETParams>
        actionRef={actionRef}
        rowKey="id"
        search={{
          labelWidth: 120,
        }}
        bordered
        pagination={false}
        toolBarRender={() => [
          <Button
            type="primary"
            key="primary"
            onClick={() => {
              handleModalVisible(true);
            }}
          >
            <PlusOutlined /> 新建
          </Button>,
          <Button
            type="primary"
            key="primary"
            onClick={() => {
              handleIconVisible(true);
            }}
          >
            <PlusOutlined /> 选择菜单
          </Button>,
        ]}
        request={menuTreeListUsingGET}
        columns={columns}
        rowSelection={{
          onChange: (_, selectedRows) => {
            setSelectedRows(selectedRows);
          },
        }}
      />
      {selectedRowsState?.length > 0 && (
        <FooterToolbar
          extra={
            <div>
              已选择{' '}
              <a
                style={{
                  fontWeight: 600,
                }}
              >
                {selectedRowsState.length}
              </a>{' '}
              项 &nbsp;&nbsp;
            </div>
          }
        >
          <Button
            onClick={async () => {
              await handleRemove(selectedRowsState);
              setSelectedRows([]);
              actionRef.current?.reloadAndRest?.();
            }}
          >
            批量删除
          </Button>
        </FooterToolbar>
      )}
      <ModalForm
        title="新建菜单"
        width="400px"
        visible={createModalVisible}
        onVisibleChange={handleModalVisible}
        onFinish={async (value) => {
          const success = await handleAdd(value as API.MenuVo);
          if (success) {
            handleModalVisible(false);
            if (actionRef.current) {
              actionRef.current.reload();
            }
          }
        }}
      >
        <ProFormText
          rules={[
            {
              required: true,
              message: '规则名称为必填项',
            },
          ]}
          width="md"
          name="name"
        />
        <ProFormTextArea width="md" name="desc" />
      </ModalForm>
      <Modal
        destroyOnClose
        width="800px"
        visible={iconPreviewVisible}
        onCancel={() => handleIconVisible(false)}
        footer={null}
      >
        <IconPreview selectIcon={selectIcon} />
      </Modal>
      <Drawer
        width={600}
        visible={showDetail}
        onClose={() => {
          setCurrentRow(undefined);
          setShowDetail(false);
        }}
        closable={false}
      >
        {currentRow?.id && (
          <ProDescriptions<API.MenuVo>
            column={2}
            title={currentRow?.name}
            request={async () => ({
              data: currentRow || {},
            })}
            params={{
              id: currentRow?.id,
            }}
            columns={columns as ProDescriptionsItemProps<API.MenuVo>[]}
          />
        )}
      </Drawer>
    </PageContainer>
  );
};

export default Menu;
